package com.sjw.smarturl.service;

import com.sjw.smarturl.entity.po.SmartUrlInfo;
import com.sjw.smarturl.repository.ISmartUrlInfoRepository;
import com.sjw.smarturl.util.BaseConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author sjw
 * @className SmartUrlService
 * @date 2020/9/1 19:06
 * @description: 短链接编码、解码
 */
@Service
public class SmartUrlService implements ISmartUrlService {

    @Autowired
    private ISmartUrlInfoRepository smartUrlInfoRepository;

    @Value("${smartUrl.errorPage}")
    private String smartUrlErrorPage;

    @Value("${smartUrl.domainName}")
    private String smartUrlDomainName;

    /**
     * 长链接编码成短链接
     *
     * @param originUrl 原始链接（长链接）
     * @return 短链接
     */
    @Override
    @Transactional
    public String encode(String originUrl) {
        SmartUrlInfo smartUrlInfo = new SmartUrlInfo(originUrl, System.currentTimeMillis());
        smartUrlInfoRepository.save(smartUrlInfo);
        // 依据MySQL自增id作为发号器，转化为62进制（只包含数字、大小写字母）
        String smartCode = BaseConvertUtil.encode10to62(smartUrlInfo.getId(), 5);
        smartUrlInfo.setSmartCode(smartCode);
        return smartUrlDomainName + "/r/" + smartCode;
    }

    /**
     * 短链接解码码短链接
     *
     * @param smartUrl 短链接
     * @return 原始链接（长链接）
     */
    @Override
    public String decode(String smartUrl) {
        // 根据62进制编码（只包含数字、大小写字母）查询原始url信息
        // 将62进制转换成十进制,根据主键直接查询
        long id = BaseConvertUtil.encode62to10(smartUrl);
        //SmartUrlInfo smartUrlInfo = smartUrlInfoRepository.findBySmartCodeAndIsdelete(smartUrl, 0);
        SmartUrlInfo smartUrlInfo = smartUrlInfoRepository.findByIdAndIsdelete((int) id, 0);
        // 初始化默认重定向跳转地址
        String originUrl = smartUrlErrorPage;
        // 更新浏览次数
        if (smartUrlInfo != null) {
            smartUrlInfo.setPageView(smartUrlInfo.getPageView() + 1);
            smartUrlInfoRepository.save(smartUrlInfo);
            originUrl = smartUrlInfo.getOriginUrl();
        }
        return originUrl;
    }
}

